from lib.settings import BITBAYS_API_URL
import urllib, hashlib, hmac, time, json
import urllib.parse
import urllib.request

def getNonce():
    return int(time.time() * 1000) + 1


def sign(params, secretkey):
    return hmac.new(secretkey.encode('utf-8'), params.encode('utf-8'), hashlib.sha512).hexdigest()


def api(uri, params, private, apikey, secretkey):
    if private:
        params['nonce'] = getNonce()
        params = urllib.parse.urlencode(params)
        headers = {
            'Key': apikey,
            'Sign': sign(params, secretkey)
        }
        req = urllib.request.Request(uri, params.encode('utf-8'), headers)
        fp = urllib.request.urlopen(req)
    else:
        req = urllib.request.Request(uri)
        fp = urllib.request.urlopen(req, timeout=1)

    if fp.status != 200:
        return False
    else:
        mybytes = fp.read()
        mystr = mybytes.decode("utf8")
        fp.close()
        return json.loads(mystr)


def sort_and_format(l, reverse=False):
    l.sort(key=lambda x: float(x[0]), reverse=reverse)
    r = []
    for i in l:
        r.append({'price': float(i[0]), 'volume': float(i[1])})
    return r
